<template>
  <section class="daily-manage">
    <div class="manage-title">新建/编辑专项答题</div>
    <section class="manage-main">
      <el-form ref="form" v-loading="formloading" :model="form" :rules="rules" label-width="150px" class="main-form">
        <el-form-item label="专项答题名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入专项答题名称"  maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="关联题库" prop="questionBank">
          <el-button v-if="!form.questionBank" size="mini" type="primary" @click="dialogPowerVisible = true">
            {{ pt === 'g' ? '选择题库分类' : '选择题库' }}
          </el-button>
          <el-tag v-else closable type="primary" @close="handleClose()" style="height: auto;white-space: normal;">
            {{ form.questionBankName }}
          </el-tag>
        </el-form-item>
        <el-form-item label="题目难度类型" prop="setQuestionType">
          <el-radio-group v-model="form.setQuestionType" @input="getType()">
            <el-radio v-for="(item, index) in dict.CTFS" :key="index" :label="item.dictValue">{{ item.dictName
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="form.setQuestionType === 'CTFS_QBSJ'">
          <el-form-item :label="pt === 'g' ? '每关出题数量' : '出题数量'" prop="questionNumber">
            <el-input v-if="pt === 'g'" v-model.number="form.questionNumber" oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="每关出题数量"  maxlength="20" show-word-limit/>
            <el-input v-else v-model.number="form.questionNumber" oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="出题数量"  maxlength="20" show-word-limit/>
          </el-form-item>

          <template v-if="pt === 'g'">
            <el-form-item v-if="pt === 'g'" label="关口数量">
              <el-input v-model.number="form.num" oninput="value=value.replace(/[^0-9]/g,'')" placeholder="请输入关口数量" />
            </el-form-item>
            <p class="tip" style="color: red; font-size: 12px; margin-left: 150px">
              *如您不输入关口数量，系统会根据每关出题数量及题库数量自动生成关口。
            </p>
          </template>

          <el-form-item label="每题分值" prop="score">
            <!-- <el-input
              v-model.number="form.score"
              oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入每题分值"
            /> -->
            <!-- <el-input-number v-model="form.score" :precision="2" /> -->
            <el-input-number v-model="form.score" :precision="2" :step="0.01" :max="999"></el-input-number>
          </el-form-item>
        </template>
        <template v-else>
          <p class="tip" style="color: red; font-size: 12px; margin-left: 150px">* 请至少填写一组出题数量和分值。</p>
          <el-form-item :label="form.setQuestionType === 'CTFS_NDSJ' ? '初级题数量' : '单选题数量'" prop="primaryQuesNum">
            <el-input v-model.number="form.primaryQuesNum" oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入出题数量"  maxlength="20" show-word-limit/>
          </el-form-item>
          <el-form-item label="每题分值" prop="primaryQuesFraction">
            <!-- <el-input
              v-model.number="form.primaryQuesFraction"
              oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入每题分值"
            /> -->
            <!-- <el-input-number v-model="form.primaryQuesFraction" :precision="2" /> -->
            <el-input-number v-model="form.primaryQuesFraction" :precision="2" :step="0.01" :max="999"></el-input-number>
          </el-form-item>

          <el-form-item :label="form.setQuestionType === 'CTFS_NDSJ' ? '中级题数量' : '多选题数量'" prop="intermediateQuesNum">
            <el-input v-model.number="form.intermediateQuesNum" oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入出题数量"  maxlength="20" show-word-limit/>
          </el-form-item>
          <el-form-item label="每题分值" prop="intermediateQuesFraction">
            <!-- <el-input
              v-model.number="form.intermediateQuesFraction"
              oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入每题分值"
            /> -->
            <!-- <el-input-number v-model="form.intermediateQuesFraction" :precision="2" /> -->
            <el-input-number v-model="form.intermediateQuesFraction" :precision="2" :step="0.01" :max="999"></el-input-number>
          </el-form-item>
          <el-form-item :label="form.setQuestionType === 'CTFS_NDSJ' ? '高级题数量' : '判断题数量'" prop="advancedQuesNum">
            <el-input v-model.number="form.advancedQuesNum" oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入出题数量"  maxlength="20" show-word-limit/>
          </el-form-item>
          <el-form-item label="每题分值" prop="advancedQuesFraction">
            <!-- <el-input
              v-model.number="form.advancedQuesFraction"
              oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入每题分值"
            /> -->
            <!-- <el-input-number v-model="form.advancedQuesFraction" :precision="2" /> -->
            <el-input-number v-model="form.advancedQuesFraction" :precision="2" :step="0.01" :max="999"></el-input-number>
          </el-form-item>
          <el-form-item :label="form.setQuestionType === 'CTFS_NDSJ' ? '技师题数量' : '填空题数量'" prop="technicianQuesNum">
            <el-input v-model.number="form.technicianQuesNum" oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入出题数量"  maxlength="20" show-word-limit/>
          </el-form-item>
          <el-form-item label="每题分值" prop="technicianQuesFraction">
            <!-- <el-input
              v-model.number="form.technicianQuesFraction"
              oninput="value=value.replace(/[^0-9]/g,'')"
              placeholder="请输入每题分值"
            /> -->
            <el-input-number v-model="form.technicianQuesFraction" :precision="2" :step="0.01" :max="999"></el-input-number>
          </el-form-item>
        </template>
        <!-- <el-form-item label="专项答题次数" prop="racticeCount">
          <el-input
            v-model.number="form.racticeCount"
            placeholder="请输入专项答题次数"
            :disabled="numberType"
            style="width: 750px; margin-right: 20px"
          />
          <el-checkbox v-model="numberType">不限</el-checkbox>
        </el-form-item> -->
        <el-form-item label="答题限时（秒）" prop="limitTime">
          <el-input v-model="form.limitTime" placeholder="请输入答题限时（秒）" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" maxlength="20" show-word-limit />
        </el-form-item>
      </el-form>
    </section>

    <div class="manage-footer">
      <el-button style="padding: 8px 30px" @click="handleCancel">取消</el-button>
      <el-button style="padding: 8px 30px" type="primary" @click="onSubmint('form')">确定</el-button>
    </div>
    <!--选择题库  -->
    <el-dialog v-el-drag-dialog custom-class="my-dialog" title="选择题库分类" :visible.sync="dialogPowerVisible" center
      width="450px" :close-on-click-modal="false">
      <choose-qs v-if="dialogPowerVisible" ref="PowerTreeFun" :is-selsct="true" @subQs="getQsFun"
        @dialogPower="dialogPower" />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogPowerVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="powerTreeFun">确定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { insert, getDictByCode, update, get } from '../api'
import ChooseQs from '@/views/skill/answerRush/components/chooseQs'
import elDragDialog from '@/directive/el-drag-dialog'
export default {
  name: 'ManageDailyPractice',
  components: { ChooseQs },
  directives: { elDragDialog },
  data() {
    return {
      formloading: false,
      dialogPowerVisible: false,
      state: 'create',
      pt: '',
      form: {
        id: '',
        setQuestionType: 'CTFS_QBSJ', // type
        name: '',
        questionBank: '',
        questionBankName: '',
        questionNumber: '',
        score: '',
        racticeCount: '',
        limitTime: '',
        primaryQuesNum: '', // 初级题数量  /   单选题数量
        primaryQuesFraction: '', // 初级题分值  /   单选题分值
        intermediateQuesNum: '', // 中级题数量  /   多选题数量
        intermediateQuesFraction: '', // 中级题分值  /   多选题分值
        advancedQuesNum: '', // 高级题数量  /   判断题数量
        advancedQuesFraction: '', // 高级题分值  /   判断题分值
        technicianQuesNum: '', // 技师题数量  /   填空题数量
        technicianQuesFraction: 0, // 技师题分值  /   填空题分值
        sort: ''
      },
      rules: {
        name: [{ required: true, message: '请输入专项答题名称', trigger: 'blur' }],
        questionBank: [{ required: true, message: '请选择题库分类', trigger: 'change' }],
        setQuestionType: [{ required: true, message: '请选择题目难度类型', trigger: 'change' }],
        questionNumber: [{ required: true, message: '请输入出题数量', trigger: 'blur' }],
        score: [{ required: true, message: '请输入每题分值', trigger: 'blur' }],
        racticeCount: [{ required: true, message: '请输入答题次数', trigger: 'blur' }],
        limitTime: [{ required: true, message: '请输入答题时间限制', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
      },
      numberType: false,
      dict: {
        CTFS: []
      }
    }
  },
  watch: {
    numberType(newVal, oldVal) {
      // console.log(newVal)
      if (newVal === true) {
        this.form.racticeCount = -1
      }
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    this.pt = this.$route.query.pt || ''
    for (const key in this.dict) {
      this.getDict(key)
    }
    if (this.$route.query.type === 'u') {
      this.getData()
    }
  },
  methods: {
    getType() {
      this.form.primaryQuesNum = ''
      this.form.primaryQuesFraction = 0
      this.form.intermediateQuesNum = ''
      this.form.intermediateQuesFraction = 0
      this.form.advancedQuesNum = ''
      this.form.advancedQuesFraction = 0
      this.form.technicianQuesNum = ''
      this.form.technicianQuesFraction = 0
      this.form.intermediateQuesNum = ''
      this.form.questionNumber = ''
      this.form.score = 0
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 编辑回显
    getData() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: this.$route.query.i })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              this.form[key] = data[key]
            }
            if (data['racticeCount'] === -1) {
              this.form.racticeCount = ''
              this.numberType = true
              this.disabled = true
            }
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    // 取消
    handleCancel() {
      this.$router.back()
    },
    // 提交
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form['type'] = 'DTLX_ZXDT'
            if (this.form.setQuestionType !== 'CTFS_QBSJ') {
              if ((this.form.primaryQuesNum === '' && this.form.primaryQuesFraction === 0) ||
                (this.form.intermediateQuesNum === '' && this.form.intermediateQuesFraction === 0) ||
                (this.form.advancedQuesNum === '' && this.form.advancedQuesFraction === 0) ||
                (this.form.technicianQuesNum === '' && this.form.technicianQuesFraction === 0)) {
                this.$message({
                  message: '请至少填写一组出题数量和分值',
                  type: 'warning'
                })
                return
              } else if (
                this.form.primaryQuesFraction === 0 &&
                this.form.intermediateQuesFraction === 0 &&
                this.form.advancedQuesFraction === 0 &&
                this.form.technicianQuesFraction === 0
              ) {
                this.$confirm('所有分值均为0，请确认是否提交?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    const loading = this.$loading({
                      lock: true,
                      text: '请稍后',
                      spinner: 'el-icon-loading',
                      background: 'rgba(0, 0, 0, 0.3)'
                    })
                    return new Promise((resolve, reject) => {
                      insert(this.form)
                        .then(() => {
                          this.dialogVisible = false
                          loading.close()
                          this.$message({
                            title: '成功',
                            message: '创建成功',
                            type: 'success',
                            duration: 2000
                          })
                          this.handleCancel()
                        })
                        .catch((error) => {
                          reject(error)
                          loading.close()
                        })
                    })
                  })
                  .catch(() => {
                    // this.$message({
                    //   type: 'info',
                    //   message: '已取消'
                    // })
                  })
              } else {
                const loading = this.$loading({
                  lock: true,
                  text: '请稍后',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.3)'
                })
                return new Promise((resolve, reject) => {
                  insert(this.form)
                    .then(() => {
                      this.dialogVisible = false
                      loading.close()
                      this.$message({
                        title: '成功',
                        message: '创建成功',
                        type: 'success',
                        duration: 2000
                      })
                      this.handleCancel()
                    })
                    .catch((error) => {
                      reject(error)
                      loading.close()
                    })
                })
              }
            } else {
              const loading = this.$loading({
                lock: true,
                text: '请稍后',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.3)'
              })
              return new Promise((resolve, reject) => {
                insert(this.form)
                  .then(() => {
                    this.dialogVisible = false
                    loading.close()
                    this.$message({
                      title: '成功',
                      message: '创建成功',
                      type: 'success',
                      duration: 2000
                    })
                    this.handleCancel()
                  })
                  .catch((error) => {
                    reject(error)
                    loading.close()
                  })
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form['type'] = 'DTLX_ZXDT'
            if (this.form.setQuestionType !== 'CTFS_QBSJ') {
              if (
                (this.form.primaryQuesNum === '' && this.form.primaryQuesFraction === 0) ||
                (this.form.intermediateQuesNum === '' && this.form.intermediateQuesFraction === 0) ||
                (this.form.advancedQuesNum === '' && this.form.advancedQuesFraction === 0) ||
                (this.form.technicianQuesNum === '' && this.form.technicianQuesFraction === 0)
              ) {
                this.$message({
                  message: '请至少填写一组出题数量和分值',
                  type: 'warning'
                })
                return
              } else if (
                this.form.primaryQuesFraction === 0 &&
                this.form.intermediateQuesFraction === 0 &&
                this.form.advancedQuesFraction === 0 &&
                this.form.technicianQuesFraction === 0
              ) {
                this.$confirm('所有分值均为0，请确认是否提交?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    const loading = this.$loading({
                      lock: true,
                      text: '请稍后',
                      spinner: 'el-icon-loading',
                      background: 'rgba(0, 0, 0, 0.3)'
                    })
                    return new Promise((resolve, reject) => {
                      update(this.form)
                        .then(() => {
                          this.dialogVisible = false
                          loading.close()
                          this.$message({
                            title: '成功',
                            message: '编辑成功',
                            type: 'success',
                            duration: 2000
                          })
                          this.handleCancel()
                        })
                        .catch((error) => {
                          reject(error)
                          loading.close()
                        })
                    })
                  })
                  .catch(() => {
                    // this.$message({
                    //   type: 'info',
                    //   message: '已取消'
                    // })
                  })
              } else {
                const loading = this.$loading({
                  lock: true,
                  text: '请稍后',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.3)'
                })
                return new Promise((resolve, reject) => {
                  update(this.form)
                    .then(() => {
                      this.dialogVisible = false
                      loading.close()
                      this.$message({
                        title: '成功',
                        message: '编辑成功',
                        type: 'success',
                        duration: 2000
                      })
                      this.handleCancel()
                    })
                    .catch((error) => {
                      reject(error)
                      loading.close()
                    })
                })
              }
            } else {
              const loading = this.$loading({
                lock: true,
                text: '请稍后',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.3)'
              })
              return new Promise((resolve, reject) => {
                update(this.form)
                  .then(() => {
                    this.dialogVisible = false
                    loading.close()
                    this.$message({
                      title: '成功',
                      message: '编辑成功',
                      type: 'success',
                      duration: 2000
                    })
                    this.handleCancel()
                  })
                  .catch((error) => {
                    reject(error)
                    loading.close()
                  })
              })
            }
          } else {
            return false
          }
        })
      }
    },
    /**
     * 关闭权限弹框
     */
    dialogPower(val) {
      this.dialogPowerVisible = val
    },
    /**
     * 确认题库
     */
    powerTreeFun() {
      this.$refs.PowerTreeFun.saveData()
      this.dialogPowerVisible = false
    },
    /**
     * 去掉某个题库
     * */
    handleClose() {
      this.form.questionBank = ''
      this.form.questionBankName = ''
    },
    /**
     * 题库
     */
    getQsFun(obj) {
      this.form.questionBankName = obj.menuName
      this.form.questionBank = obj.menuIds
      this.$refs['form'].validateField('questionBank', (val) => {
        if (!val) {
          return true
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.daily-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px;
      /*对垂直流动条有效*/
      height: 1px;
      /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }
  }

  .main-form {
    width: 1000px !important;
    margin: 0 auto;

    .line {
      text-align: center;
    }

    .form-card {
      margin-top: 20px;

      .el-card__body {
        max-width: 90%;
        margin: 0 auto;
      }
    }

    .rankImg {
      width: 100px;
      height: 100px;
      margin-left: 150px;
      margin-bottom: 20px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}</style>
